﻿using DAO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DAO.Repositories;
using WebApplication.Models;

namespace WebApplication.Controllers
{
    public abstract class CRUDController<T, M> : Controller 
		where T : class
        where M : class, IModel<T>
    {
        
        public CRUDController()
        {
        }

        protected abstract BaseRepository<T> Repository { get; }
        protected abstract DataManager Dm { get; }

        public virtual ActionResult List(string search)
        {
            if (!string.IsNullOrEmpty(search))
                return View(Repository.GetAll());//.Where(t => t.Name.Contains(search)));
            return View(Repository.GetAll());
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(M entity)
        {
            if (!ModelState.IsValid)
            {
                ViewData["errors"] = "Объект не валиден";
                return View(entity);
            }
            Repository.Add(entity.ToEfEntity());
            Dm.SaveChanges();
            return RedirectToAction("List");
        }

        public ActionResult Edit(int id)
        {
            return View(Repository.GetById(id));
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(T entity)
        {
            if (!ModelState.IsValid)
            {
                ViewData["errors"] = "Объект не валиден";
                return View(entity);
            }
            Repository.Edit(entity);
            Dm.SaveChanges();
            return RedirectToAction("List");
        }

        public ActionResult Delete(int id)
        {
            Repository.Delete(id);
            Dm.SaveChanges();
            return RedirectToAction("List");
        }

        public ActionResult Details(int id)
        {
            return View(Repository.GetById(id));
        }
    }
}